package com.pool.socket;

import java.net.*;
import java.nio.ByteBuffer;
import java.util.*;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.pool.socket.DataType.MessageFormat;
import com.pool.socket.DataType.SocketDepict;

public class DataReceiver extends Thread {

	SocketServer server;
	Socket conn;
	CircularBuffer buffer;
	static long receiverId = 0;

	public DataReceiver(SocketServer server, Socket socket) {
		this.server = server;
		conn = socket;
		buffer = new CircularBuffer(256);
		this.setName("SocketReceiver" + receiverId++);
	}

	public void notifyHandler(int gatewayId, byte[] data) {
		Queue<DataHandler> handlers = SocketServer.getHandlers();
		DataHandler handler = null;
		synchronized (handlers) {

			if (!handlers.isEmpty()) {
				handler = (DataHandler) handlers.poll();
				handler.fillProperty(gatewayId, data, conn);
				synchronized (handler) {
					handler.notify();
				}
			} else {
				System.out.println("Handler list size = " + handlers.size());
			}
		}
		if (handler == null) {

			handler = new DataHandler();
			handler.fillProperty(gatewayId, data, conn);
			handler.start();
		}
	}

	public void run() {
		byte[] bytes = new byte[16 * 1024];
		try {
			while (!conn.isClosed()) {
				int len = conn.getInputStream().read(bytes);
				if (len > 0) {
					buffer.pushData(bytes, len);
					int gatewayId = buffer.setValidPos();
					// System.out.println("local Gateway id = " + gatewayId);
					if (gatewayId > 0) {
						byte[] data = buffer.removeData();
						notifyHandler(gatewayId, data);
					}
				} else { // other side close this socket
					SocketObserver.closeSocket(conn);
					break; // exit while loop
				}
			}
		} catch (Exception e) {
			System.out.println("Client exception happen " + e.getMessage());
			e.printStackTrace();
		}
	}
}
